// pages/cart/cart.js
const app = getApp()

Page({
  data: {
    cartItems: [],
    selectAllStatus: true, // 默认全选
    totalPrice: 0,
    totalQuantity: 0
  },

  onLoad() {
    this.loadCartData()
  },

  onShow() {
    this.loadCartData()
  },

  loadCartData() {
    const cart = app.globalData.cart || []
    // 初始化选中状态（仅第一次加载时）
    const initializedCart = cart.map(item => {
      if (item.selected === undefined) {
        item.selected = true // 默认选中
      }
      return item
    })
    
    this.calculateTotal(initializedCart)
    this.setData({
      cartItems: initializedCart
    })
    this.saveCart(initializedCart)
  },

  calculateTotal(cart) {
    return cart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  },

  // 计算总价和总数
  calculateTotal(cart) {
    let totalPrice = 0
    let totalQuantity = 0
    let allSelected = true
    
    cart.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.quantity
        totalQuantity += item.quantity
      }
      if (!item.selected) allSelected = false
    })

    this.setData({
      totalPrice: totalPrice.toFixed(2),
      totalQuantity,
      selectAllStatus: allSelected
    })
  },

  // 单个商品选中状态切换
  toggleItemSelect(e) {
    const index = e.currentTarget.dataset.index
    const cart = this.data.cartItems
    cart[index].selected = !cart[index].selected
    
    this.calculateTotal(cart)
    this.setData({ cartItems: cart })
    this.saveCart(cart)
  },


  // 全选/取消全选
  toggleSelectAll() {
    const selectAll = !this.data.selectAllStatus
    const cart = this.data.cartItems.map(item => {
      item.selected = selectAll
      return item
    })
    
    this.setData({
      cartItems: cart,
      selectAllStatus: selectAll
    })
    this.calculateTotal(cart)
    this.saveCart(cart)
  },

  // 保存购物车状态
  saveCart(cart) {
    app.globalData.cart = cart
    wx.setStorageSync('cart', cart)
  },

  // 减少数量
  decreaseQuantity(e) {
    const { id } = e.currentTarget.dataset
    // 只查找一次商品
    const item = this.data.cartItems.find(item => item.id === id)
    if (!item) {
        wx.showToast({
            title: '商品不存在',
            icon: 'none'
        })
        return
    }

    if (item.quantity > 1) {
        // 更新数量
        const success = app.updateQuantity(id, item.quantity - 1, item.specs || 'MR')
        if (success) {
            this.loadCartData()
        } else {
            wx.showToast({
                title: '更新失败',
                icon: 'none'
            })
        }
    } else {
        this.removeItem(e)
    }
  },



  // 移除商品
  removeItem(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          const id = e.currentTarget.dataset.id;
          const specs = this.data.cartItems.find(item => item.id === id).specs;
          app.removeItem(id,specs)
          this.loadCartData()
        }
      }
    })
  },

  // 去结算
  checkout() {
    if (this.data.cartItems.length === 0) {
      wx.showToast({ title: '购物车为空', icon: 'none' })
      return
    }
    wx.navigateTo({
      url: '/pages/order/confirm'
    })
  }
})